package com.htandroid.htandroid.adapter;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.ab.soap.AbSoapUtil;
import com.htandroid.htandroid.R;
import com.htandroid.htandroid.global.MyApplication;
import com.htandroid.htandroid.tools.ToolLog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MyAdapter_listcggl extends BaseAdapter {
    ArrayList<Map<String, Object>> data = new ArrayList<Map<String, Object>>();

    private HashMap<Integer, Boolean> isSelected;
    //用来传递单价修改状态
    private HashMap<Integer, String> IpriceUpdated;
    //用来传递金额修改状态
    private HashMap<Integer, String> IamountUpdated;
    // 上下文
    Context context;
    // 用来导入布局
    FrameLayout lvparent;
    TextView tv_cgdorder;
    Double amount;
    Double price;
    Double quantity;
    double sum = 0.00;
    String title = "";

    // 构造器
    public MyAdapter_listcggl(Context context, ArrayList<Map<String, Object>> data,
                              FrameLayout lvparent, TextView tv_cgdorder, String title) {
        this.data = data;
        this.context = context;
        this.lvparent = lvparent;
        this.tv_cgdorder = tv_cgdorder;
        this.title = title;
        isSelected = new HashMap<Integer, Boolean>();
        IpriceUpdated = new HashMap<Integer, String>();
        IamountUpdated = new HashMap<Integer, String>();
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int position) {
        return data.get(position);
    }

    @Override
    public long getItemId(int position) {
        return (Integer.valueOf(data.get(position).get("index").toString()) - 1);
//        ToolLog.log("+++++++++++++++++++++++++++++++++++position:" + position);
//        ToolLog.log("===================================index:" + (Integer.valueOf(data.get(position).get("index").toString()) - 1));
//        return position;
    }

    @Override
    public View getView(final int position, View convertView, final ViewGroup parent) {
        ViewHolder holder = null;
        if (convertView == null) {
            holder = new ViewHolder();
            // 导入布局并赋值给convertview
            convertView = LayoutInflater.from(this.context).inflate(R.layout.basenvo_item_listcggl, parent, false);

            holder.background = (ImageView) convertView.findViewById(R.id.item_iv);
            holder.index = (TextView) convertView.findViewById(R.id.item_index);
            holder.cdepname_tv = (TextView) convertView.findViewById(R.id.cdepname_tv);
            holder.cinvstd_tv = (TextView) convertView.findViewById(R.id.cinvstd_tv);
            holder.cinvunit_tv = (TextView) convertView.findViewById(R.id.cinvunit_tv);
            holder.iquantity_tv = (TextView) convertView.findViewById(R.id.iquantity_tv);
            holder.cinvcode_tv = (TextView) convertView.findViewById(R.id.cinvcode_tv);
            holder.cvenname_tv = (TextView) convertView.findViewById(R.id.cvenname_tv);
            holder.edit_iamount = (TextView) convertView.findViewById(R.id.edit_iamount);
            holder.edit_iprice = (TextView) convertView.findViewById(R.id.edit_iprice);
            holder.edit_iv = (ImageView) convertView.findViewById(R.id.edit_iv);
            holder.editover_iv = (ImageView) convertView.findViewById(R.id.editover_iv);
            holder.more = (ImageView) convertView.findViewById(R.id.item_btn_more);
            holder.inum_tv = (TextView) convertView.findViewById(R.id.inumt_tv);
            holder.inum = (TextView) convertView.findViewById(R.id.inum);
            holder.hsiprice_tv = (TextView) convertView.findViewById(R.id.hsiprice_tv);
            holder.hsiamount_tv = (TextView) convertView.findViewById(R.id.hsiamount_tv);
            holder.hanshui = (LinearLayout) convertView.findViewById(R.id.hanshui);
            holder.priceandamount = (LinearLayout) convertView.findViewById(R.id.priceandamount);
            if ("请购生成订单".equals(title)) {
                holder.inum.setVisibility(View.GONE);
                holder.inum_tv.setVisibility(View.GONE);
                holder.hanshui.setVisibility(View.GONE);
            } else if ("订单生成收货".equals(title) || "订单生成直拨".equals(title)) {
                holder.priceandamount.setVisibility(View.GONE);
            }
            holder.more.setTag(position);

            //监听编辑按钮
            final ViewHolder finalHolder = holder;
//            finalHolder.edit_iprice.setOnKeyListener(new View.OnKeyListener() {
//                @Override
//                public boolean onKey(View view, int i, KeyEvent keyEvent) {
//                    if (keyEvent != null && keyEvent.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
//                        InputMethodManager in = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
//                        in.hideSoftInputFromWindow(view.getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
//                        changePrice(finalHolder, position);
//                        //软键盘回车后自动关闭编辑状态
//                        finalHolder.editover_iv.performClick();
//                        return true;
//                    }
//                    return false;
//                }
//            });
//
//            finalHolder.edit_iamount.setOnKeyListener(new View.OnKeyListener() {
//                @Override
//                public boolean onKey(View view, int i, KeyEvent keyEvent) {
//                    if (keyEvent != null && keyEvent.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
//                        InputMethodManager in = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
//                        in.hideSoftInputFromWindow(view.getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
//                        changeAmount(finalHolder, position);
//                        //软键盘回车后自动关闭编辑状态
//                        finalHolder.editover_iv.performClick();
//                        return true;
//                    }
//                    return false;
//                }
//            });

//            finalHolder.edit_iprice.setOnTouchListener(new View.OnTouchListener() {
//                @Override
//                public boolean onTouch(View view, MotionEvent event) {
//                    if (event.getAction() == MotionEvent.ACTION_UP) {
//                        flag = position;
//                    }
//                    return false;
//                }
//            });
//
//            finalHolder.edit_iamount.setOnTouchListener(new View.OnTouchListener() {
//                @Override
//                public boolean onTouch(View view, MotionEvent event) {
//                    if (event.getAction() == MotionEvent.ACTION_UP) {
//                        flag = position;
//                    }
//                    return false;
//                }
//            });
//
//            finalHolder.edit_iprice.setOnFocusChangeListener(new View.OnFocusChangeListener() {
//                @Override
//                public void onFocusChange(View v, boolean hasFocus) {
//                    //失去焦点
//                    if (!hasFocus) {
//                        changePrice(finalHolder, position);
//                    } else {
//                    }
//                }
//            });
//
//            finalHolder.edit_iamount.setOnFocusChangeListener(new View.OnFocusChangeListener() {
//                @Override
//                public void onFocusChange(View v, boolean hasFocus) {
//                    if (!hasFocus) {
//                        changeAmount(finalHolder, position);
//                    }
//                }
//            });
//
//            holder.edit_iv.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    //点击进入编辑状态
//                    finalHolder.edit_iv.setVisibility(View.GONE);
//                    finalHolder.editover_iv.setVisibility(View.VISIBLE);
//                    finalHolder.edit_iprice.setBackgroundResource(R.drawable.edit_background);
//                    finalHolder.edit_iprice.setTextColor(Color.WHITE);
//                    finalHolder.edit_iamount.setBackgroundResource(R.drawable.edit_background);
//                    finalHolder.edit_iamount.setTextColor(Color.WHITE);
//
//                    //允许编辑
//                    finalHolder.edit_iprice.setEnabled(true);
//                    finalHolder.edit_iprice.setFocusable(true);
//                    finalHolder.edit_iprice.setFocusableInTouchMode(true);
//                    finalHolder.edit_iprice.setClickable(true);
//
//                    finalHolder.edit_iprice.clearFocus();
//                    finalHolder.edit_iamount.clearFocus();
//
//                    finalHolder.edit_iamount.setEnabled(true);
//                    finalHolder.edit_iamount.setFocusable(true);
//                    finalHolder.edit_iamount.setFocusableInTouchMode(true);
//                    finalHolder.edit_iamount.setClickable(true);
//
//                    finalHolder.edit_iprice.requestFocus();
//                    finalHolder.edit_iamount.requestFocus();
//                }
//            });
//
//            //监听编辑完成按钮
//            holder.editover_iv.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    //点击进入完成编辑
//                    finalHolder.edit_iv.setVisibility(View.VISIBLE);
//                    finalHolder.editover_iv.setVisibility(View.GONE);
//                    finalHolder.edit_iprice.setTextColor(finalHolder.cinvstd_tv.getCurrentTextColor());
//                    finalHolder.edit_iprice.setBackgroundColor(Color.TRANSPARENT);
//                    finalHolder.edit_iamount.setTextColor(finalHolder.cinvstd_tv.getCurrentTextColor());
//                    finalHolder.edit_iamount.setBackgroundColor(Color.TRANSPARENT);
//
//                    //允许编辑
//                    finalHolder.edit_iprice.setEnabled(false);
//                    finalHolder.edit_iprice.setFocusable(false);
//                    finalHolder.edit_iprice.setFocusableInTouchMode(false);
//                    finalHolder.edit_iprice.setClickable(false);
//
//                    finalHolder.edit_iamount.setEnabled(false);
//                    finalHolder.edit_iamount.setFocusable(false);
//                    finalHolder.edit_iamount.setFocusableInTouchMode(false);
//                    finalHolder.edit_iamount.setClickable(false);
//                    finalHolder.edit_iprice.clearFocus();
//                    finalHolder.edit_iamount.clearFocus();
//
//                    //保存数据
////                    data.get(position).put("iprice", finalHolder.edit_iprice.getText());
////                    IpriceUpdated.put(position, finalHolder.edit_iprice.getText().toString());
////                    data.get(position).put("iamount", finalHolder.edit_iamount.getText());
////                    IamountUpdated.put(position, finalHolder.edit_iamount.getText().toString());
//                }
//            });

            holder.more.setOnClickListener(new MyOnClickListener(holder.cinvunit_tv) {
                @Override
                public void onClick(View v) {
                    final ImageView img = (ImageView) v;
                    //弹出窗口后,变更更多图标
                    img.setImageResource(R.drawable.item_more_choose);
                    View dialog = LayoutInflater.from(context).inflate(R.layout.basenvo_cgglitem_moreview, null, false);
                    final PopupWindow popupWindow = new PopupWindow(dialog, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);
                    popupWindow.setTouchable(true);
                    popupWindow.setOutsideTouchable(true);
                    popupWindow.setBackgroundDrawable(new BitmapDrawable());
                    popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                        public void onDismiss() {
                            //还原图标
                            img.setImageResource(R.drawable.item_more);
                        }
                    });
                    //more
                    TextView more_tv1 = (TextView) dialog.findViewById(R.id.item_more_tv1);
                    TextView more_tv2 = (TextView) dialog.findViewById(R.id.item_more_tv2);
                    TextView more_tv3 = (TextView) dialog.findViewById(R.id.item_more_tv3);
                    TextView more_tv4 = (TextView) dialog.findViewById(R.id.item_more_tv4);
                    TextView more_tv5 = (TextView) dialog.findViewById(R.id.item_more_tv5);
                    TextView more_tv6 = (TextView) dialog.findViewById(R.id.item_more_tv6);
                    TextView more_tv7 = (TextView) dialog.findViewById(R.id.item_more_tv7);
                    TextView more_tv8 = (TextView) dialog.findViewById(R.id.item_more_tv8);
                    TextView more_tv9 = (TextView) dialog.findViewById(R.id.item_more_tv9);
                    TextView more_tv10 = (TextView) dialog.findViewById(R.id.item_more_tv10);
                    ImageView more_close = (ImageView) dialog.findViewById(R.id.item_close);
                    if ("请购生成订单".equals(title)) {
                        more_tv1.setText(data.get(position).get("data1").toString());
                        more_tv2.setText(data.get(position).get("data2").toString());
                        more_tv3.setText(data.get(position).get("data3").toString());
                        more_tv4.setText(data.get(position).get("data4").toString());
                        more_tv5.setText(data.get(position).get("data5").toString());
                        more_tv6.setText(data.get(position).get("data6").toString());
                        more_tv7.setVisibility(View.GONE);
                        more_tv8.setText(data.get(position).get("data8").toString());
                        more_tv9.setText(data.get(position).get("data9").toString());
                        more_tv10.setText(data.get(position).get("data10").toString());
                    } else if ("订单生成收货".equals(title) || "订单生成直拨".equals(title)) {
                        more_tv1.setText(data.get(position).get("data1").toString());
                        more_tv2.setText(data.get(position).get("data2").toString());
                        more_tv3.setText(data.get(position).get("data3").toString());
                        more_tv4.setText(data.get(position).get("data4").toString());
                        more_tv5.setText(data.get(position).get("data5").toString());
                        more_tv6.setText(data.get(position).get("data6").toString());
                        more_tv7.setText(data.get(position).get("data7").toString());
                        more_tv8.setText(data.get(position).get("data8").toString());
                        more_tv9.setText(data.get(position).get("data9").toString());
                        more_tv10.setText(data.get(position).get("data10").toString());
                    }

                    more_close.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            popupWindow.dismiss();
                        }
                    });
                    //dialog.setY(v.getY());
                    AnimationSet animationSet = new AnimationSet(true);

                    ScaleAnimation scaleAnimation = new ScaleAnimation(0, 1, 1, 1, Animation.ZORDER_BOTTOM, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                    animationSet.setDuration(250);
                    animationSet.addAnimation(scaleAnimation);
                    dialog.startAnimation(animationSet);
                    //处理最后一个item 浮动窗口 显示不全
                    DisplayMetrics dm = new DisplayMetrics();
                    int[] position = new int[2];
                    dm = context.getResources().getDisplayMetrics();
                    int screenHeight = dm.heightPixels; // 屏幕高（像素，如：800px）
                    getRootivew().getLocationInWindow(position);
                    int rootViewY = position[1] + getRootivew().getHeight() + 10;
                    int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
                    int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
                    dialog.measure(w, h);
                    int popupWindowHeight = dialog.getMeasuredHeight();
                    if (rootViewY + popupWindowHeight < screenHeight) {
                        popupWindow.showAsDropDown(getRootivew());
                    } else {
                        popupWindow.showAsDropDown(getRootivew(), 0, screenHeight - (rootViewY + popupWindowHeight));
                    }
                }
            });
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        if (data != null) {
            //convertView.setTag(R.id.tag_first, data.get(position).get("index"));
            if (holder.index != null) {
                holder.index.setText(data.get(position).get("index").toString());
            }
            if (holder.cdepname_tv != null) {
                holder.cdepname_tv.setText(data.get(position).get("cdepname").toString());
            }
            if (holder.cinvcode_tv != null) {
                holder.cinvcode_tv.setText("(" + data.get(position).get("cinvcode").toString() + ") " +
                        data.get(position).get("cinvname").toString());
            }
            if (holder.cinvstd_tv != null) {
                holder.cinvstd_tv.setText(data.get(position).get("cinvstd").toString());
            }
            if (holder.cinvunit_tv != null) {
                holder.cinvunit_tv.setText(data.get(position).get("cinvm_unit").toString());
            }
            if (holder.cvenname_tv != null) {
                holder.cvenname_tv.setText(data.get(position).get("cvenname").toString());
            }
            if (holder.iquantity_tv != null) {
                holder.iquantity_tv.setText(data.get(position).get("iquantity").toString());
            }
            if ("请购生成订单".equals(title)) {
                if (holder.edit_iamount != null) {
                    holder.edit_iamount.setText(data.get(position).get("iamount").toString());
                    IamountUpdated.put(position, data.get(position).get("iamount").toString());
                }
                if (holder.edit_iprice != null) {
                    holder.edit_iprice.setText(data.get(position).get("iprice").toString());
                    IpriceUpdated.put(position, data.get(position).get("iprice").toString());
                }
            }
            if ("订单生成收货".equals(title) || "订单生成直拨".equals(title)) {
                if (holder.inum_tv != null) {
                    holder.inum_tv.setText(data.get(position).get("inum").toString());
                }
                if (holder.hsiprice_tv != null) {
                    holder.hsiprice_tv.setText(data.get(position).get("hsiprice").toString());
                }
                if (holder.hsiamount_tv != null) {
                    holder.hsiamount_tv.setText(data.get(position).get("hsiamount").toString());
                    IamountUpdated.put(position, data.get(position).get("hsiamount").toString());
                }
            }
//            if ("true".equals(data.get(position).get("" + position).toString().trim())) {
//                holder.background.setImageResource(R.drawable.itembox_choose);
//                holder.edit_iv.setEnabled(true);
//            } else {
//                holder.edit_iv.setEnabled(false);
//                holder.background.setImageResource(R.drawable.itembox_zi);
//            }
            int index = Integer.valueOf(data.get(position).get("index").toString()) - 1;
            if (isSelected.size() > 0 && isSelected.size() > index) {
                if (getIsSelected().get(index)) {
                    //选中
                    holder.background.setImageResource(R.drawable.itembox_choose);
                    holder.edit_iv.setEnabled(true);
                } else {
                    //未选
                    holder.edit_iv.setEnabled(false);
                    holder.background.setImageResource(R.drawable.itembox_zi);
                }
            }
        }
        return convertView;
    }

    public void notifyDataSetChanged() {
        super.notifyDataSetChanged();
    }

    public double sumAmount(ArrayList<Map<String, Object>> adatperDataList) {
        sum = 0.00;
        String a = "";
        // 遍历list的长度，判断是否选中
        HashMap<Integer, Boolean> selectlist = getIsSelected();
        //获取金额修改状态
        List<Boolean> list = new ArrayList<>();
        for (Map.Entry<Integer, Boolean> entry : selectlist.entrySet()) {
            if (entry.getValue() == true) {
                list.add(entry.getValue());
            }
        }
        if (list.size() > 0) {
            for (int i = 0; i < selectlist.size(); i++) {
                if (selectlist.get(i) == true) {
                    if ("请购生成订单".equals(title)) {
                        a = adatperDataList.get(i).get("iamount").toString();
                    } else if ("订单生成收货".equals(title) || "订单生成直拨".equals(title)) {
                        a = adatperDataList.get(i).get("hsiamount").toString();
                    }
                    if (a == null) {
                        selectlist.put(i, false);
                        a = "0.00";
                    }
                    sum += Double.parseDouble(a);
                }
            }
        } else {
            sum = 0.00;
        }
        return sum;
    }

//    public double sumAmount(ArrayList<Map<String, Object>> adatperDataList) {
//        sum = 0.00;
//
//        // 遍历list的长度，判断是否选中
//        HashMap<Integer, Boolean> selectlist = getIsSelected();
//        //获取金额修改状态
//        HashMap<Integer, String> IamountUpdated = getIamountUpdated();
//        List<String> list = new ArrayList<>();
//        for (int i = 0; i < adatperDataList.size(); i++) {
//            String isSelect = adatperDataList.get(i).get("" + i).toString();
//            if (isSelect == "true") {
//                list.add(isSelect);
//            }
//        }
//        if (list.size() > 0) {
//            for (int i = 0; i < adatperDataList.size(); i++) {
//                if ("true".equals(adatperDataList.get(i).get("" + i).toString())) {
//                    String a = IamountUpdated.get(i);
//                    if (a == null) {
//                        //adatperDataList.get(i).put("" + i, "false");
//                        a = "0.00";
//                    }
//                    sum += Double.parseDouble(a);
//                }
//            }
//        } else {
//            sum = 0.00;
//        }
//        return sum;
//    }

    public HashMap<Integer, Boolean> getIsSelected() {
        return isSelected;
    }

    public HashMap<Integer, String> getIpriceUpdated() {
        return IpriceUpdated;
    }

    public void setIsSelected(HashMap<Integer, Boolean> isSelected) {
        this.isSelected = isSelected;
    }

    public HashMap<Integer, String> getIamountUpdated() {
        return IamountUpdated;
    }

    private class ViewHolder {
        ImageView background;
        TextView index;
        TextView cdepname_tv;
        TextView cinvstd_tv;
        TextView cinvunit_tv;
        TextView iquantity_tv;
        TextView edit_iamount;
        TextView cinvcode_tv;
        TextView cvenname_tv;
        TextView edit_iprice;
        ImageView edit_iv, editover_iv;
        ImageView more;
        TextView inum_tv;
        TextView hsiprice_tv;
        TextView hsiamount_tv;
        LinearLayout hanshui;
        LinearLayout priceandamount;
        TextView inum;
    }

    private class MyOnClickListener implements View.OnClickListener {
        private View rootView;

        public MyOnClickListener(View view) {
            rootView = view;
        }

        public View getRootivew() {
            return rootView;
        }

        @Override
        public void onClick(View view) {

        }
    }
}
